package design;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author pengfei.hpf
 * @date 2020/3/5
 * @verdion 1.0.0
 */
public class ValidWordAbbr {
    Map<String, String> map;
    Map<String, List<String>> abMap;
    public ValidWordAbbr(String[] dictionary) {
        map = new HashMap<>();
        abMap = new HashMap<>();
        if(dictionary == null || dictionary.length == 0){
            return;
        }
        for(String s: dictionary){
            if(s.length() <= 2){
                continue;
            }
            String ab = getAbbr(s);
            abMap.computeIfAbsent(ab, x -> new ArrayList<>()).add(s);
            map.put(s, ab);
        }
    }

    public boolean isUnique(String word) {
        if(word.length() <= 2){
            return true;
        }
        // if word not in dic?
        String ab = map.get(word);

        if(ab == null){
            ab = getAbbr(word);
        }
        return (map.containsKey(word) && abMap.get(ab).size() == 1) || (!map.containsKey(word) && abMap.get(ab)==null);
    }

    private String getAbbr(String s){
        if(s.length() <= 2){
            return s;
        }
        int len = s.length();
        StringBuilder builder = new StringBuilder();
        builder.append(s.charAt(0));
        builder.append(len -2);
        builder.append(s.charAt(len -1));
        return builder.toString();
    }

    public static void main(String[] args){

        ValidWordAbbr va = new ValidWordAbbr(new String[]{"door","naive"});
        System.out.println(va.isUnique("cat"));
        System.out.println(va.isUnique("cat"));
    }
}
